from flask import Flask, request, jsonify, render_template
import pymysql

app = Flask(__name__)

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'your_username',
    'password': 'your_password',
    'database': 'your_database',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

@app.route('/')
def home():
    return render_template('index.html')  # 确保你的 index.html 在 templates 文件夹中

@app.route('/diary', methods=['POST'])
def add_diary_entry():
    data = request.json
    date = data.get('date')
    weather = data.get('weather')
    mood = data.get('mood')
    events = data.get('events')

    try:
        connection = pymysql.connect(**db_config)
        with connection.cursor() as cursor:
            sql = "INSERT INTO diary_entries (date, weather, mood, events) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (date, weather, mood, events))
            connection.commit()
            return jsonify({'message': 'Diary entry added successfully.'}), 200
    except pymysql.Error as e:
        print("Database error:", str(e))  # 添加详细的错误日志
        return jsonify({'error': str(e)}), 500
    except Exception as e:
        print("General error:", str(e))  # 捕获其他异常
        return jsonify({'error': str(e)}), 500
    finally:
        if connection:
            connection.close()


if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)
